/**
 * Created by Jerry on 16/9/20.
 */
angular.module('mamApp').controller('loginController', ['$scope', 'AuthManager', '$state', 'api', function ($scope, AuthManager, $state, api) {

   $scope.user = {};
    $scope.err = {};
    // $scope.bgSelect = 0;
    $scope.bgClick = function (index) {
        $scope.bgSelect = index;
    }

    if (localStorage.getItem("userInfo")) {
        var tmpUserInfo = JSON.parse(localStorage.getItem("userInfo"));
        $scope.user = tmpUserInfo.remember ? tmpUserInfo : {};
    }
    function randomString(len) {
        len = len || 32;
        var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
        var maxPos = $chars.length;
        var pwd = '';
        for (var i = 0; i < len; i++) {
            pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return pwd;
    }

    var randomCode = "";

    $scope.codeRefrsh = function () {
        randomCode = randomString(12);
        $scope.code = api + "/code/kaptcha?key=" + randomCode;
    }
    $scope.codeRefrsh();
    // setInterval(function () {
    //     if ($scope.bgSelect == 2) {
    //         $scope.$apply($scope.bgSelect = 0)
    //     } else {
    //         $scope.$apply($scope.bgSelect = $scope.bgSelect + 1);
    //     }
    // }, 5000)

    $scope.login = function () {
        if ($scope.user.userName && $scope.user.password && $scope.user.validateCode) {
            AuthManager.login({
                userName: $scope.user.userName,
                password: $scope.user.password,
                validateCode: $scope.user.validateCode
            }, randomCode).then(function (result) {
                if (result.data.c == "s") {
                    if ($scope.user.remember) {
                        result.data.userCpVO.remember = $scope.user.remember;
                        result.data.userCpVO.password = $scope.user.password;
                    }
                    localStorage.setItem("userInfo", JSON.stringify(result.data.userCpVO));
                    $state.go("main.home")
                } else {
                    $scope.err.password = result.data.i;
                    $scope.codeRefrsh();
                }
            })
        } else if (!$scope.user.userName) {
            $scope.err.password = "用户名不能为空";
        } else if (!$scope.user.password) {
            $scope.err.password = "密码不能为空"

        }else {
            $scope.err.password = "验证码不能为空"
        }

    };

    $scope.keyup=function (e) {

        if(e.key=="Enter"){
            $scope.login();
        }
    }
}])

